package com.example.smartcity_ikun_new2.ui.home.NewsFragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.smartcity_ikun_new2.AppContext
import com.example.smartcity_ikun_new2.R
import com.example.smartcity_ikun_new2.databinding.FragmentNews2Binding
import com.example.smartcity_ikun_new2.databinding.FragmentNews4Binding
import com.example.smartcity_ikun_new2.logic.network.SmartCityNetWorkCreate
import com.example.smartcity_ikun_new2.ui.home.adapter.NewsListViewAdapter
import com.example.smartcity_ikun_new2.ui.home.model.NewsEntity

class NewsFragment4 : Fragment() {
    private val viewModel by lazy {
        ViewModelProviders.of(this).get(NewsViewModel::class.java)
    }

    private lateinit var mBinding: FragmentNews4Binding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = FragmentNews4Binding.inflate(inflater, container, false)

        val arrayNewsAdapter = ArrayList<NewsEntity>()
        // 根据type类型加载新闻
        viewModel.setNewsType(20)
        viewModel.newsListLiveData.observe(this, Observer {
            if (it.code == 200) {
                arrayNewsAdapter.clear()
                viewModel.newsList.clear()
                viewModel.newsList.addAll(it.rows)
            }

            for (i in viewModel.newsList){
                arrayNewsAdapter.add(
                    NewsEntity(
                        SmartCityNetWorkCreate.baseUrl + i.cover,
                        i.title,
                        i.content,
                        i.publishDate,
                        i.commentNum.toString() + "评论"
                    )
                )
                mBinding.NewsList.adapter?.notifyItemInserted(arrayNewsAdapter.size)
            }

            mBinding.NewsList.apply {
                this.layoutManager = LinearLayoutManager(context)
                this.adapter = NewsListViewAdapter(arrayNewsAdapter)
            }
        })

        return mBinding.root
    }
}